import 'dart:async';
import 'dart:io';

import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';

import 'controller/MediaStreamingManager.dart';

class PLDroidMediaStreaming {
  static const MethodChannel _channel =
      const MethodChannel('PLDroidMediaStreaming');
  static const EventChannel _eventChannel =
      const EventChannel('PLDroidMediaStreamingEventChannel');

  static StreamSubscription<dynamic> addListener(void onData(dynamic event),{Function onError, void onDone(), bool cancelOnError}) {
    return _eventChannel.receiveBroadcastStream().listen(onData, onError: onError, onDone: onDone, cancelOnError: cancelOnError);
  }

  static Future removeLocalView(int viewId) async {
    await _channel.invokeMethod('removeLocalView', {
      "viewId": viewId
    });
  }

  /// Creates the video renderer Widget.
  ///
  /// The Widget is identified by viewId, the operation and layout of the Widget are managed by the app.
  static Widget createNativeView(Function(int viewId) created, {Key key, MediaStreamingManager manager}) {
    if (Platform.isIOS) {
      return UiKitView(
        key: key,
        viewType: 'PLDroidMediaStreamingRenderView',
        creationParamsCodec: const StandardMessageCodec(),
        creationParams: manager?.toJson(),
        onPlatformViewCreated: (viewId) {
          if (created != null) {
            created(viewId);
          }
        },
      );
    } else {
      return AndroidView(
        key: key,
        viewType: 'PLDroidMediaStreamingRenderView',
        creationParamsCodec: const StandardMessageCodec(),
        creationParams: manager?.toJson(),
        onPlatformViewCreated: (viewId) {
          if (created != null) {
            created(viewId);
          }
        },
      );
    }
  }
}
